package fina2.dcs.returns;

import java.util.List;

import javax.annotation.Resource;
import javax.ejb.Stateless;
import javax.ejb.TransactionManagement;
import javax.ejb.TransactionManagementType;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.UserTransaction;

import org.apache.log4j.Logger;
import org.jboss.annotation.ejb.LocalBinding;

@Stateless
@LocalBinding(jndiBinding = "ImportReturnSession/local")
@TransactionManagement(TransactionManagementType.BEAN)
public class ImportReturnSession implements ImportReturnLocal {

	private Logger log = Logger.getLogger(getClass());

	@Resource
	private UserTransaction ut;

	@PersistenceContext
	private EntityManager em;

	public void addReturn(ImportReturn ir) {
		synchronized (ImportReturnSession.class) {
			try {
				ut.begin();
				log.info("Adding Return " + ir);

				Integer max = (Integer) em.createQuery("SELECT MAX(u.id)+1 FROM " + ImportReturn.class.getName() + " u").getSingleResult();
				if (max == null) {
					max = 0;
				}
				ir.setId(max);
				em.persist(ir);
				ut.commit();
			} catch (Exception ex) {

				log.error(ex.getMessage(), ex);
				try {
					ut.rollback();
				} catch (Exception exx) {
					// TODO
				}
			}

			log.info("Return Added");
		}
	}

	public void addReturns(List<ImportReturn> irs) {
		if (irs != null)
			for (ImportReturn ir : irs)
				addReturn(ir);
	}

	public int getMaxReturnId() {
		Integer max = 0;
		try {

			max = (Integer) em.createQuery("SELECT MAX(u.id)+1 FROM " + ImportReturn.class.getName() + " u").getSingleResult();
			if (max == null) {
				max = 0;
			}

		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
		}
		return max;
	}

	@Override
	public ImportReturn findById(int id) {
		return em.find(ImportReturn.class, id);
	}

}
